//
//  VoiceView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/4.
//

import SwiftUI
import AVFAudio
import Combine

//语音试图
struct VoiceView: View {
    var bean: SoundBean?
    @State var player : AVAudioPlayer!
    @State var sound : ImageResource = .homeIconSound3
    
    var body: some View {
        HStack(spacing: 0) {
            Image(sound)
                .resizable()
                .frame(width: 15, height: 15)
            Text("13")
                .font(.system(size: 10))
                .padding(.horizontal, 3)
            Text("''")
                .font(.system(size: 10))
            Spacer()
        }.frame(width: 100,height: 24)
            .padding(.horizontal,5)
            .background(.bgItem)
            .cornerRadius(100)
            .contentShape(Rectangle())
            .onTapGesture {
                if AudioPlayerManager.shared.isPlaying() {
                    showToast("正在播放中，请稍后")
                    return
                }
                var num = 1
                let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
                    .sink { _ in
                        switch num {
                        case 1:
                            sound = .homeIconSound1
                        case 2:
                            sound = .homeIconSound2
                        default:
                            sound = .homeIconSound3
                        }
                        if (num == 3) {
                            num = 1
                        } else {
                            num = num + 1
                        }
                    }
                AudioPlayerManager.shared.playUrl(from: "http://cdn.aiyuxm.com/imprint/testtest")
                AudioPlayerManager.shared.onPlaybackFinished = {
                    timer.cancel()
                    sound = .homeIconSound3
                    showLog("播放结束")
                }
            }
        
    }
}

#Preview {
    VoiceView()
}
